<template>
    <div class="common-layout">
      <el-container>
        <el-main>
    <el-row>
        <el-table :data="state.data" height="900" style="width: 100%;" :fit=true
        :cell-class-name="tableCellClassName"
        @sort-change="sortChange"
        @cell-click="cellClick"
        :default-sort="state.sort"
        :summary-method="summaryMethod"
        show-summary >
            <el-table-column prop="date" label="date" width="120" sortable fixed/>
            <el-table-column v-if="!stock" prop="day" label="星期" width="80">
                <template #default="scope">
                    {{ getDayOfWeek(scope.row.date) }}
                </template> 
            </el-table-column>
            <el-table-column prop="time" label="时间" width="100" />
            <el-table-column prop="display" label="display" width="100">
                <template #default="scope">
                    <ToDDisplay :stock="scope.row.stock" :date="scope.row.date" />
                </template>
            </el-table-column>
            <el-table-column prop="drawdown" label="drawdown" width="100" sortable/>
            <el-table-column prop="curPct" label="curPct" width="100" sortable/>
            <el-table-column prop="optCurPct" label="optCurPct" width="100" sortable/>
            <el-table-column prop="operation" label="operation" width="100"/>
            <el-table-column prop="pct" label="pct"/>
            <el-table-column prop="desc" label="desc"/>
            <el-table-column prop="levelPoint" label="分位点"/>
            <el-table-column prop="operateNum" label="手数"/>
            <el-table-column prop="price" label="价格" width="100" sortable/>
            <el-table-column prop="amount" label="总金额" width="120" sortable/>
            <el-table-column prop="indicator" label="指标" width="100" show-overflow-tooltip/>
            <el-table-column prop="reason" label="原因" width="160" show-overflow-tooltip/>
            <el-table-column prop="nextOperate" label="后续操作" width="200" show-overflow-tooltip/>
        </el-table>
    </el-row>
    </el-main>
    </el-container>
    </div>
</template>

<script setup>
import { reactive, watch } from 'vue';
import { getSessionStorage, setSessionStorage } from '@/utils/help';
import { formatCurrency, getLpClassName } from '@/utils/help';
import { getLastedOperation } from '@/service/operation';
import { getDayOfWeek } from '@/utils/help';
import { weekStockSearch } from '@/stores/week'
import { storeToRefs } from 'pinia';
import { useRoute } from 'vue-router'
import ToDDisplay from '../element/ToDDisplay.vue';

const baseKey = "LastedOperation"
const selectKey = baseKey + "Select"
const sortPropKey = baseKey + "SortProp"
const sortOrderKey = baseKey + "SortOrder"

const stockSearchStore = weekStockSearch()
let { input } = storeToRefs(stockSearchStore)

const state = reactive({
    rawData: [],
    operationSelected: "",
    operationSelectedStock: "",
    data: [],
    selected: getSessionStorage(selectKey) || '全部',
    sort: { 
        prop: getSessionStorage(sortPropKey) || 'date' , 
        order: getSessionStorage(sortOrderKey) || 'desc' 
    }
})

// 网址传参
const {query: query} = useRoute()
if(query.stock) {
    input.value = query.stock
    state.operationSelectedStock = query.stock
}

const loadData = () => {
    getLastedOperation(state.operationSelectedStock).then( res => {
        state.rawData = res.data
        state.data = res.data
    })
}

// 只监听pinia中某一个值的变化
watch(() => input.value, (newValue, oldValue) => {
    state.operationSelectedStock = newValue
    loadData()
})
        
loadData()

const sortChange = (column, prop, order) => {
    setSessionStorage(sortPropKey, column.prop)
    setSessionStorage(sortOrderKey, column.order)
}

const cellClick = (row, column, cell, event) => {
    let columnProperty = column.property
    let val = row[columnProperty]

    if (columnProperty == 'stock') {
        // 点相同的股票名则取消选择
        if (state.operationSelectedStock != "" && state.operationSelectedStock == val) {
            state.operationSelectedStock = ""
        } else {
            state.operationSelectedStock = val
        }
        // 重新请求数据
        loadData()
    }

    if (['operation','date','indicator','desc'].includes(columnProperty)) {
        if (state.operationSelected != "" && state.operationSelected == val) {
            state.operationSelected = ""
            state.data = state.rawData
        } else {
            state.operationSelected = val
            state.data = state.rawData.filter(item => item[columnProperty] == val)
        }
    }
}


const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {
    var columnProperty = column.property
    var v = row[columnProperty]
    if (columnProperty == 'operation') {
        if (v == "卖出") {
            return 'lt0-cell';
        } else if ( v == '买入') {
            return 'wugu-lt100-cell'
        } else if ( v == '分红') {
            return 'lpgt99-cell'
        } else if ( v == '模拟买入') {
            return 'lplt10-cell'
        } else if ( v == '模拟卖出') {
            return 'wugu-gt1000-cell'
        }
    }
    if (columnProperty == 'levelPoint') {
        if (v) {
            return getLpClassName(v)
        }
    }
    if (['curPct','optCurPct','pct','d10MaxPct'].includes(columnProperty)) {
        if (v < 0) {
            return 'lt0-cell'
        }
    }
    if (columnProperty == 'drawdown') {
        if (v == 0) {
            return 'wugu-lt100-cell'
        }
    }
    return ''
}
const summaryMethod = (param) => { 
    const { columns, data } = param;
    const sums = [];

    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '汇总：';
            return;
        }

        if (["amount","operateNum"].includes(column.property)) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                const validValues = values.filter(value => !isNaN(value));
                if (validValues.length > 0) {
                    const sum = validValues.reduce((prev, curr) => prev + curr, 0);
                    sums[index] = `${sum.toFixed(2)}`;
                }
            }
        }
    })

    return sums;
}
</script>

<style>
</style>